//
//  ActivityViewController.m
//  UGoods
//
//  Created by 宝银 on 16/1/15.
//  Copyright © 2016年 蓝鸥科技.李贺. All rights reserved.
//

#import "ActivityViewController.h"
#import "BaseTableView.h"
#import "ActivityModel.h"
#import "LHAFNetworkTool.h"
#import "ActivityTableViewCell.h"
#import <MJRefresh.h>
#import "BaseCollectionView.h"
#import "FindModel.h"
#import "GoodsCollectionViewCell2.h"
#import "BuyDetailViewController.h"
#import "TopicsDetailViewController.h"
#import "BaseView.h"
#import "BaseLabel.h"
#import "ConstantsDefine.h"
@interface ActivityViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) BaseTableView *tableView;
@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, retain) NSMutableArray *listArray;
@property (nonatomic, retain) BaseCollectionView *collectionView;

@end

@implementation ActivityViewController

- (void)dealloc
{
    [_tableView release];
    [_dataArray release];
    [_listArray release];
    [_collectionView release];
    [super dealloc];
}

- (void)handleData {
    NSString *str = @"http://api.ujipin.com/v2/app/ios/phone/v3/special/getZtList?channel=appstore&idfa=1EF25F55-6367-4567-B0D5-82DF4F1557CD&user_id=470825&plantform=iphone&version=314";
    [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        NSArray *array = resposeObject[@"data"][@"list"];
        self.dataArray = [ActivityModel modelHandleWithArray:array];
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"请求失败：%@", error);
    }];
}

- (void)handleHeaderData {
    NSString *str = @"http://api.ujipin.com/v2/app/ios/phone/v3/index/getFlashSaleList?channel=appstore&idfa=1EF25F55-6367-4567-B0D5-82DF4F1557CD&user_id=470825&plantform=iphone&version=314";
    [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        NSArray *array = resposeObject[@"data"][@"list"];
        
        self.listArray = [FindModel modelHandleWithArray:array];
        
        [self.collectionView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
         NSLog(@"请求失败：%@", error);
    }];
}

// 下拉刷新
- (void)addHeaderRefresh {
    
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        [self.dataArray removeAllObjects];
        [self handleData];
        
        [self.listArray removeAllObjects];
        [self handleHeaderData];
    }];
    // 设置普通状态的动画图片
    NSArray *idleImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态
    NSArray *pullingImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:pullingImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    NSMutableArray *refreshingImages = [NSMutableArray array];
    for (NSInteger i = 0; i < 24; i++) {
        [refreshingImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"loading_%ld", i]]];
    }
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    // 设置所有数据加载完毕的动画图片
    NSArray *NoMoreDataImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:NoMoreDataImages forState:MJRefreshStateNoMoreData];
    
    self.tableView.mj_header = header;
    
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    // 隐藏状态
    header.stateLabel.hidden = YES;
    
    [self.tableView.mj_header beginRefreshing];
}


// 创建TableViewHeader
- (void)createTableViewHeader {
    BaseView *backView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 210 * HEIGHT)];
    self.tableView.tableHeaderView = backView;
    [backView release];
    
    BaseLabel *alabel = [[BaseLabel alloc] initWithFrame:CGRectMake(10 * WIDTH, 5 * HEIGHT, 200 * WIDTH, 20 * HEIGHT)];
    alabel.text = @"限时抢购";
    alabel.font = [UIFont systemFontOfSize:15 * WIDTH];
    [backView addSubview:alabel];
    [alabel release];
    
    UICollectionViewFlowLayout *layout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    layout.itemSize = CGSizeMake(130 * WIDTH, 170 * HEIGHT);
    layout.minimumInteritemSpacing = 10 * WIDTH;
    layout.minimumLineSpacing = 10 * HEIGHT;
    layout.sectionInset = UIEdgeInsetsMake(0, 5 * WIDTH, 0, 5 * WIDTH);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 30 * WIDTH, self.view.frame.size.width, 170 * HEIGHT) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [backView addSubview:_collectionView];
    [_collectionView release];
    [layout release];
    [_collectionView registerClass:[GoodsCollectionViewCell2 class] forCellWithReuseIdentifier:@"cell"];
}

// cell 个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _listArray.count;
}

// cell设置
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // section: 分区
    // item：表示cell
    
    // 获取cell
    GoodsCollectionViewCell2 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    FindModel *model = _listArray[indexPath.item];
    cell.model = model;
    //    cell.backgroundColor = [UIColor redColor];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    BuyDetailViewController *buy = [[BuyDetailViewController alloc] init];
    FindModel *model = _listArray[indexPath.item];
    buy.goods_id = [NSString stringWithFormat:@"%@", model.myID];
    [self.navigationController pushViewController:buy animated:YES];
    [buy release];
}



// 创建TableView
- (void)createTableView {
    self.tableView = [[BaseTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
    [_tableView registerClass:[ActivityTableViewCell class] forCellReuseIdentifier:@"cell"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * identifier = @"cell";
    ActivityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[ActivityTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    ActivityModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 280 * HEIGHT;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    TopicsDetailViewController *top = [[TopicsDetailViewController alloc] init];
    FindModel *model = self.dataArray[indexPath.row];
    top.model = model;
    [self.navigationController pushViewController:top animated:YES];
    [top release];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self handleData];
    [self handleHeaderData];
    [self createTableView];
    if (self.listArray.count != 0) {
        [self createTableViewHeader];
    }
    
    [self addHeaderRefresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
